package network;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-03-07
 * Time: 9:14
 */
public class TcpEchoClient {
    private Socket socket = null;
    //要和服务器通信 就需要先知道服务器所在的位置

    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        // 这个new操作完成之后, 就完成了tcp的建立
        socket = new Socket(serverIp, serverPort);
    }

    public void start() {
        System.out.println("客户端启动!");
        Scanner scannerConsole = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            while (true) {
                // 从控制台输入字符串
                System.out.println("->");
                String request = scannerConsole.next();
                // 2. 把请求发送给服务端
                PrintWriter writer = new PrintWriter(outputStream);
                //    使用 println 带上换行. 后续服务器读取请求, 就可以使用 scanner.next 来获取了
                writer.println(request);
                writer.flush();
                //3. 从服务器读响应
                Scanner scannerNetwork = new Scanner(inputStream);
                String response = scannerNetwork.next();
                System.out.println(response);
            }
        }catch (IOException exception) {
            exception.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
